/**
 * @func 导出Excel
 */
import { saveAs } from 'file-saver'
import ExcelJS from 'exceljs'
const exportExcel = async (that, columns, exclude, data, excelName) => {
  const loading = that.$msgLoading('正在导出...', 0)
  const workbook = new ExcelJS.Workbook()

  const sheet = workbook.addWorksheet(excelName, { views: [{ showGridLines: true }] })
  const headerCell = new Array(columns?.length ?? 99).fill('A')
  const headers = columns
    .map((item) => {
      if (!exclude.includes(item.dataIndex)) {
        return {
          header: item.title,
          key: item.dataIndex,
        }
      }
    })
    .filter(Boolean)

  sheet.columns = headers
  headers.forEach((_, index) => {
    sheet.getCell(String(headerCell[index]) + String(1)).font = {
      bold: true,
    }
  })
  data.forEach((item) => {
    sheet.addRow(item)
  })

  const buffer = await workbook.xlsx.writeBuffer()

  saveAs(new Blob([buffer]), `${excelName}.xlsx`)
  that.$msgSuc('导出成功')
  loading()
}

export { exportExcel }
